<template>
  <div>
    <div ref="chartContainer" :style="{ width: '100%', height: '300px' }" />
  </div>
</template>

<script setup>
import { dataURLtoBlob } from "@/utils/common";
import * as echarts from "echarts";
import { computed, onUnmounted, ref, watch } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();

const chartContainer = ref(null);
let chartInstance = null;
const props = defineProps({
  chartsData: {
    type: Object,
    required: true
  },
  type: {
    type: String,
    default: ""
  },
  className: {
    type: String,
    default: ""
  },
  startTime: {
    type: String,
    default: ""
  },
  endTime: {
    type: String,
    default: ""
  }
});

const options = computed(() => {
  return {
    tooltip: {
      trigger: "item"
    },
    legend: {
      bottom: "",
      left: "center"
    },
    series: [
      {
        type: "pie",
        center: ["50%", "55%"],
        radius: "50%",
        data: props.chartsData.missingTypeStatMap,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        },
        color: ["#14C7C7", "#FFB266", "#8B8AE6", "#407DF1", "#13C4C3", "#F1A861", "#8180D9"],
        label: {
          show: true,
          formatter: function (params) {
            // 使用 \n 实现换行
            return params.value + "\n" + params.name + ": " + params.percent + "%";
          }
        }
      }
    ]
  };
});

const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    chartInstance.setOption(options.value);
    chartInstance.on("click", params => {
      router.push(
        `/all/safeManage/defect?className=${props.className}&missingType=${params?.data?.code}&startTime=${props.startTime}&endTime=${props.endTime}`
      );
    });
  }
};

const downLoad = () => {
  const img64 = chartInstance.getDataURL({
    type: "png",
    pixelRatio: 2,
    backgroundColor: "#fff"
  });
  const blob = dataURLtoBlob(img64);
  const imgSrc = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = imgSrc;
  link.style.display = "none";
  link.setAttribute("download", "缺失类型占比");
  document.body.appendChild(link);
  link.click();
  URL.revokeObjectURL(link.href);
  document.body.removeChild(link);
};

defineExpose({
  downLoad
});

watch(
  () => props.chartsData,
  chartsData => {
    initChart();
  }
);
onUnmounted(() => {
  chartInstance && chartInstance.dispose();
});
</script>
